package com.xpec.canaan.util;

import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;

public class CompareSingleDirectoryRecorder extends Thread {
	
	public CompareSingleDirectoryRecorder(String originalPath, String newPath, String recorderName, CompareUnderDirectory mainthread)
	{
		m_originalPath = originalPath;
		m_newPath = newPath;
		m_recorderName = recorderName;
		m_mainThread = mainthread;
	}
	
	public void run()
	{
		CompareResultRecorder result = getCompareResult();
		m_mainThread.addCompareResult(result);
	}
	
	public CompareResultRecorder getCompareResult()
	{
		LoadMD5Recorder originalRecord = new LoadMD5Recorder(m_originalPath + "\\" + CompareResultRecorder.CompareFileName);
		LoadMD5Recorder newRecord = new LoadMD5Recorder(m_newPath + "\\" + CompareResultRecorder.CompareFileName);
		Hashtable<String, String> ortable;
		Hashtable<String, String> newtable;
		
		CompareResultRecorder recorder = new CompareResultRecorder(m_recorderName);
		
		try
		{
			ortable = originalRecord.parserFileMD5();
			newtable = newRecord.parserFileMD5();
			compareTable(ortable, newtable, recorder);
		}
		catch(Exception exp)
		{
			System.err.println("error occur: " + exp.getMessage());
			recorder.setIsEquals(false);
		}
		
		return recorder;
	}
	
	private void compareTable(Hashtable<String, String> ortable, Hashtable<String, String> newtable, CompareResultRecorder recorder)
	{
		Set<String> orset = ortable.keySet();
		Iterator<String> oritr = orset.iterator();
		
		while( oritr.hasNext() )
		{
			String key = oritr.next();
			String newValue = newtable.get(key);
			String orValue = ortable.get(key);
			// compare if original file more than new file
			if( null == newValue )
			{
				recorder.addDeletedFile(key);
			}
			else if( !newValue.equals(orValue) )
			{
				recorder.setIsEquals(false);
			}
		}
	}
	
	private String m_recorderName;
	private String m_originalPath;
	private String m_newPath;
	private CompareUnderDirectory m_mainThread;
}
